import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/popular',
    name: 'popular',
    component: () => import('../views/PopularView.vue')
  },
  {
    path: '/categories',
    name: 'categories',
    component: () => import('../views/CategoriesView.vue')
  },
  {
    path: '/category/:categoryId',
    name: 'categoryFoods',
    component: () => import('../views/CategoryFoodsView.vue')
  },
  {
    path: '/restaurants',
    name: 'restaurants',
    component: () => import('../views/RestaurantsView.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/user/dashboard',
    name: 'userDashboard',
    component: () => import('../views/user/UserDashboard.vue'),
    meta: { requiresAuth: true, role: 'user' }
  },
  {
    path: '/merchant/dashboard',
    name: 'merchantDashboard',
    component: () => import('../views/merchant/MerchantDashboard.vue'),
    meta: { requiresAuth: true, role: 'merchant' }
  },
  {
    path: '/admin/dashboard',
    name: 'adminDashboard',
    component: () => import('../views/admin/AdminDashboard.vue'),
    meta: { requiresAuth: true, role: 'admin' }
  },
  {
    path: '/food/:id',
    name: 'foodDetail',
    component: () => import('../views/FoodDetailView.vue')
  },
  {
    path: '/merchant/:id',
    name: 'merchantDetail',
    component: () => import('../views/MerchantDetailView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的位置，则返回到保存的位置
    if (savedPosition) {
      return savedPosition
    }
    // 如果有锚点，则滚动到锚点位置
    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth',
      }
    }
    // 否则滚动到页面顶部
    return { top: 0, behavior: 'smooth' }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('userRole')
  
  // 如果路由需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next('/login')
    } else if (to.meta.role && to.meta.role !== userRole) {
      next('/')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
